<template>
    <view class="he-switch" :class="[value == true ? 'he-switch--on' : '', disabled ? 'he-switch--disabled' : '']" @tap="onClick">
        <view class="he-switch__node node-class"></view>
    </view>
</template>

<script>
export default {
    name: "he-switch",
    props: {
        // 是否为禁用装填
        disabled: {
            type: Boolean,
            default: false
        },
        // 通过v-model双向绑定的值
        value: {
            type: Boolean,
            default: false
        },
        // 是否使手机发生短促震动，目前只在iOS的微信小程序有效(2020-05-06)
        vibrateShort: {
            type: Boolean,
            default: false
        },
        // 打开选择器时的值
        activeValue: {
            type: [Number, String, Boolean],
            default: true
        },
        // 关闭选择器时的值
        inactiveValue: {
            type: [Number, String, Boolean],
            default: false
        },
    },
    methods: {
        onClick() {
            if (!this.disabled) {
                // 使手机产生短促震动，微信小程序有效，APP(HX 2.6.8)和H5无效
                if(this.vibrateShort) uni.vibrateShort();
                this.$emit('input', !this.value);
                // 放到下一个生命周期，因为双向绑定的value修改父组件状态需要时间，且是异步的
                this.$nextTick(() => {
                    this.$emit('change', this.value ? this.activeValue : this.inactiveValue);
                });
            }
        }
    }
};
</script>

<style lang="scss" scoped>

.he-switch {
    position: relative;
    display: inline-block;
    box-sizing: initial;
    width: 72px;
    height: 40px;
    background-color: #cccccc;
    border-radius: 20px;
    transition: background-color 0.3s;
}
.he-switch__node {
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    top: 50%;
    left: 4px;
    width: 32px;
    height: 32px;
    transform: translateY(-50%);
    border-radius: 100%;
    z-index: 1;
    background-color: #fff;
    background-color: #fff;
    box-shadow: 0 3px 1px 0 rgba(0, 0, 0, 0.05), 0 2px 2px 0 rgba(0, 0, 0, 0.1), 0 3px 3px 0 rgba(0, 0, 0, 0.05);
    box-shadow: 0 3px 1px 0 rgba(0, 0, 0, 0.05), 0 2px 2px 0 rgba(0, 0, 0, 0.1), 0 3px 3px 0 rgba(0, 0, 0, 0.05);
    transition: transform 0.3s cubic-bezier(0.3, 1.05, 0.4, 1.05);
    transition: transform 0.3s cubic-bezier(0.3, 1.05, 0.4, 1.05), -webkit-transform 0.3s cubic-bezier(0.3, 1.05, 0.4, 1.05);
    transition: transform cubic-bezier(0.3, 1.05, 0.4, 1.05);
    transition: transform 0.3s cubic-bezier(0.3, 1.05, 0.4, 1.05)
}
.he-switch--on {
    @include background_color("background_color");
}
.he-switch--on .he-switch__node {
    transform: translateX(100%) translateY(-50%);
}
.he-switch--disabled {
    opacity: 0.4;
}
</style>
